// Program: ata
// Description: Creates all ATA compatible block devices.
//

//
// main.cc -- Defines the main startup routine, and runloop.
//

#include "../udev/UdevFilesystem_IF.h"
#include <string.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <jimix/IRQDispatcher.h>
#include <jimix/ResourceManager.h>
#include "AtaDevice.h"

extern "C" void yield();

AtaDevice *devices[4];

static void ata_handler(int sig)
{
  switch(sig)
  {
  case 18:
    devices[0]->deviceReady();
  }
}

int main(char argc, char **argv)
{
  
  // Register our IRQ handler.
  signal(18, &ata_handler);
  u32int irqDispatcher = requestResource((char*)"IRQDispatcher");
  callResource(irqDispatcher, IRQDispatcher_IF::registerHandler, 14, getpid(), 18);
  
  FILE *console= fopen("/dev/console", "w");
  
  devices[0] = new AtaDevice();
  
  char model[41];
  devices[0]->getModelName(model, 41);
  model[40] = '\0';
  fprintf(console, "[ata\t] Found device '%s'.\n", model);
  fprintf(console, "[ata\t] Device has %d heads, %d cylinders, %d sectors p/track.\n",
         devices[0]->getHeads(), devices[0]->getCylinders(), devices[0]->getSectorsPerTrack());
  PartitionInfo p = devices[0]->getPartitionInfo(0);
  fclose(console);
  
  u32int devfs = requestResource("devfs");
  u32int resourceManager = requestResource("ResourceManager");
  
  char *name = (char*)"hd";
  char *shared_name = (char*)callResource(resourceManager, ResourceManager_IF::share, name, 3);
  
  u32int major = 0;
  u32int minor = -1;
  callResource(devfs, UdevFilesystem_IF::makedev, shared_name, true,
               (major<<16)|minor, devices[0]->resource);
  
  for(int i = 0; i < 4; i++)
  {
    PartitionInfo p = devices[0]->getPartitionInfo(i);
    if (p.type == 0x00)
      continue;
    
    major = 0;
    minor = i+1;
    callResource(devfs, UdevFilesystem_IF::makedev, shared_name, true,
                 (major<<16)|minor, devices[0]->resource);
  }
  
  devices[0]->clearCache();
  for(;;)
    yield();
}
